<template>
  <div class="chat-container">
    <el-container style="height: 100vh">
      <el-header style="border-bottom: 1px solid #eee; display: flex; align-items: center;">
        <h2>DeepSeek Chat</h2>
      </el-header>
      
      <el-main class="chat-main">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.role]"
        >
          <div class="message-content">
            <div class="message-avatar">
              <el-avatar :src="message.role === 'user' ? userAvatar : assistantAvatar" />
            </div>
            <div class="message-text">
              <div v-if="message.role === 'user'" class="user-text">
                {{ message.content }}
              </div>
              <div v-else class="assistant-text">
                <div v-if="message.isStreaming" class="streaming-text">
                  <span v-html="formatStreamingText(message.content)"></span>
                  <span class="cursor">|</span>
                </div>
                <div v-else v-html="formatText(message.content)"></div>
              </div>
            </div>
          </div>
        </div>
        
        <div v-if="loading" class="message assistant">
          <div class="message-content">
            <div class="message-avatar">
              <el-avatar :src="assistantAvatar" />
            </div>
            <div class="message-text">
              <div class="assistant-text">
                <div class="streaming-text">
                  <span class="cursor">|</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-main>
      
      <el-footer class="input-footer">
        <div class="input-container">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="2"
            placeholder="输入消息..."
            @keyup.enter.exact.prevent="sendMessage"
          />
          <el-button 
            type="primary" 
            class="send-button" 
            @click="sendMessage"
            :disabled="!inputMessage.trim() || loading"
          >
            发送
          </el-button>
        </div>
        <div class="tips">
          <el-text type="info">DeepSeek Chat 可能会产生不准确或冒犯性的信息</el-text>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 头像URL - 替换为你自己的
const userAvatar = 'https://avatars.githubusercontent.com/u/1?v=4';
const assistantAvatar = 'https://avatars.githubusercontent.com/u/2?v=4';

const inputMessage = ref('');
const messages = ref([]);
const loading = ref(false);

// 格式化普通文本
const formatText = (text) => {
  return text.replace(/\n/g, '<br>');
};

// 格式化流式文本
const formatStreamingText = (text) => {
  return text.replace(/\n/g, '<br>');
};

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message) return;

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: message,
    isStreaming: false
  });

  inputMessage.value = '';
  
  // 添加空的助手消息用于流式响应
  const assistantMessage = {
    role: 'assistant',
    content: '',
    isStreaming: true
  };
  messages.value.push(assistantMessage);
  
  loading.value = true;
  const key= 'sk-0f777cc5cd974461bfc767c898c5601e';
  const baseURL = import.meta.env.DEV ? '/api' : 'https://api.deepseek.com';
  try {
    // 
    // 这里替换为你的API端点 https://api.deepseek.com
    const response = await fetch('/apiAI/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
         'Authorization': 'Bearer ' + key
        // 'Authorization': 'Bearer ' + import.meta.env.VITE_DEEPSEEK_API_KEY // 替换为你的API密钥
      },
      body: JSON.stringify({
        model: 'deepseek-chat',
        messages: messages.value
          .filter(m => !m.isStreaming)
          .map(m => ({ role: m.role, content: m.content })),
        stream: true
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let done = false;

    while (!done) {
      const { value, done: readerDone } = await reader.read();
      done = readerDone;
      
      if (value) {
        const chunk = decoder.decode(value, { stream: true });
        const lines = chunk.split('\n').filter(line => line.trim() !== '');
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.substring(6);
            if (data === '[DONE]') {
              done = true;
              break;
            }
            
            try {
              const parsed = JSON.parse(data);
              if (parsed.choices && parsed.choices[0].delta && parsed.choices[0].delta.content) {
                assistantMessage.content += parsed.choices[0].delta.content;
              }
            } catch (e) {
              console.error('Error parsing JSON:', e);
            }
          }
        }
      }
    }
  } catch (error) {
    console.error('Error:', error);
    ElMessage.error('发送消息失败: ' + error.message);
    // 移除流式消息
    messages.value.pop();
  } finally {
    assistantMessage.isStreaming = false;
    loading.value = false;
  }
};
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.el-header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  z-index: 10;
}

.chat-main {
  flex: 1;
  overflow-y: auto;
  padding: 20px 16px 0;
  display: flex;
  flex-direction: column;
  gap: 24px;
  background: linear-gradient(180deg, #f7f9fc 0%, #f0f2f5 100%);
  scroll-behavior: smooth;
}

.message {
  max-width: 90%;
  transition: all 0.3s ease;
}

.message.user {
  align-self: flex-end;
}

.message.assistant {
  align-self: flex-start;
}

.message-content {
  display: flex;
  gap: 16px;
}

.message.user .message-content {
  flex-direction: row-reverse;
}

.message-text {
  padding: 16px;
  border-radius: 18px;
  max-width: calc(100% - 60px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
}

.message:not(:last-child) {
  margin-bottom: 8px;
}

.message:hover .message-text {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.user-text {
  background-color: #5a8dee;
  color: white;
  border-radius: 18px 18px 4px 18px;
}

.assistant-text {
  background-color: #fff;
  color: #1a1a1a;
  border-radius: 18px 18px 18px 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.message-avatar .el-avatar {
  width: 42px;
  height: 42px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.message:hover .message-avatar .el-avatar {
  transform: scale(1.05);
}

.streaming-text {
  min-height: 24px;
  line-height: 1.6;
  font-size: 15px;
}

.cursor {
  animation: blink 1.2s infinite;
  font-weight: bold;
  color: #5a8dee;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}

.input-footer {
  padding: 16px 24px;
  background-color: #fff;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.08);
  border-radius: 20px 20px 0 0;
  z-index: 10;
}

.input-container {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
  align-items: flex-end;
}

:deep(.el-textarea__inner) {
  border-radius: 16px;
  border: 1px solid #e0e4e9;
  background: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04) inset;
  font-size: 15px;
  line-height: 1.5;
  padding: 12px 56px 12px 20px;
  resize: none;
  transition: all 0.3s ease;
}

:deep(.el-textarea__inner):focus {
  border-color: #5a8dee;
  box-shadow: 0 0 0 4px rgba(90, 141, 238, 0.15);
}

.send-button {
  border-radius: 14px;
  height: 54px;
  padding: 0 22px;
  font-weight: 500;
  font-size: 16px;
  letter-spacing: 0.5px;
  background-color: #5a8dee;
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(90, 141, 238, 0.3);
}

.send-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(90, 141, 238, 0.4);
}

.send-button:disabled {
  opacity: 0.5;
  transform: none;
  box-shadow: none;
}

.tips {
  text-align: center;
  margin-top: 8px;
}

:deep(.el-text) {
  font-size: 13px;
  opacity: 0.7;
}

/* 聊天区域滚动条美化 */
.chat-main::-webkit-scrollbar {
  width: 8px;
}

.chat-main::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.03);
  border-radius: 4px;
}

.chat-main::-webkit-scrollbar-thumb {
  background: rgba(90, 141, 238, 0.3);
  border-radius: 4px;
}

.chat-main::-webkit-scrollbar-thumb:hover {
  background: rgba(90, 141, 238, 0.5);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .message {
    max-width: 95%;
  }
  
  .message-text {
    padding: 14px;
    font-size: 15px;
  }
  
  .message-avatar .el-avatar {
    width: 36px;
    height: 36px;
  }
  
  .input-footer {
    padding: 12px 16px;
  }
  
  :deep(.el-textarea__inner) {
    padding: 10px 16px;
  }
  
  .send-button {
    height: 46px;
    padding: 0 18px;
    font-size: 15px;
  }
}

@media (max-width: 480px) {
  .el-header h2 {
    font-size: 18px;
  }
  
  .message-content {
    gap: 12px;
  }
  
  .chat-main {
    padding: 16px 12px 0;
    gap: 16px;
  }
  
  .input-container {
    gap: 12px;
  }
}
</style>